/* gs_utils.c -- Utilidades diversas
 *
 * Copyright (C) 2007-2008, Diogo F. S. Ramos <diogo.ramos@usp.br>
 * GEAR - Grupo de Estudos Avançados em Robótica
 * <http://www.sel.eesc.usp.br/gear>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdio.h"
#include "config.h"
#include "gs_utils.h"


/** Recupera o caminho de um arquivo dentro do diretório "data".
 *
 * O trunfo desta função é o fato dela buscar o arquivo indepentende
 * de onde o programa foi executado.
 *
 * @param *argv Nome do programa que esta sendo executado.
 *
 * @param *file Nome do arquivo a ser procurado.
 *
 * @return Caminho para o arquivo procurado.
 */
gchar * 
gs_utils_get_file_inside_data( const char *argv, const char * file )
{
    gchar *progname = NULL;
    gchar *xml_file = NULL;    

    progname = g_find_program_in_path (argv);
    if (progname)
    {
	static const gchar *SEPsrcSEPgtkpod = G_DIR_SEPARATOR_S "src" G_DIR_SEPARATOR_S "gearserial";

	if (!g_path_is_absolute (progname))
	{
	    gchar *cur_dir = g_get_current_dir ();
	    gchar *prog_absolute;

	    if (g_str_has_prefix (progname, "." G_DIR_SEPARATOR_S))
		prog_absolute = g_build_filename (cur_dir,progname+2,NULL);
	    else
		prog_absolute = g_build_filename (cur_dir,progname,NULL);
	    g_free (progname);
	    g_free (cur_dir);
	    progname = prog_absolute;
	}

	if (g_str_has_suffix (progname, SEPsrcSEPgtkpod))
	{
	    gchar *suffix = g_strrstr (progname, SEPsrcSEPgtkpod);
	    if (suffix)
	    {
		*suffix = 0;
		xml_file = g_build_filename (progname, "data", file, NULL);
	    }
	}
	g_free (progname);
	if (xml_file && !g_file_test (xml_file, G_FILE_TEST_EXISTS))
	{
	    g_free (xml_file);
	    xml_file = NULL;
	}
    }
    if (!xml_file)
	xml_file = g_build_filename (PACKAGE_DATA_DIR,
				     PACKAGE_NAME,
				     "data",
				     file,
				     NULL);
    else
    {
	/* printf ("Usando arquivo local:\n%s\n", xml_file); */
    }

    return xml_file;
}
